<?php
namespace App\Services;
use Elasticsearch\ClientBuilder;

class ElasticSearchService
{
    private $client;
    private $index;
    public function __construct() {
        $elastic        = config('elastic');
        $serve          = $elastic['host']. ':' .$elastic['port'];
        $this->index    = $elastic['index'];
        $this->client   = ClientBuilder::create()->setHosts([$serve])->build();
        if (empty($this->index)) {
            throw new Exception("ElasticSearch的索引为空");
        }
    }

    /**
     * 添加文档
     * @param $id
     * @param $body
     */
    public function add($id, $body) {
        $params = [
            'index' => $this->index,
            'id'    => $id,
            'body'  => $body
        ];

        $this->client->create($params);
    }

    /**
     * 删除文档
     * @param $id
     */
    public function delete($id) {
        $params = [
            'index' => $this->index,
            'id'    => $id
        ];
        $this->client->delete($params);
    }

    /**
     * 修改文档
     * @param $id
     * @param $data
     */
    public function update($id, $data) {
        $params = [
            'index' => $this->index,
            'id'    => $id,
            // 'type'  => 'all',
            'body'  => [
                'doc'   => $data
            ]
        ];
        $this->client->update($params);
    }

    /**
     * 获取单条
     * @param $id
     * @return array|callable
     */
    public function get($id) {
        $params = [
            'index' => $this->index,
            'id'    => $id
        ];

        return $this->client->getSource($params);
    }

    /**
     * 查询数据
     * @param array $query
     * @return array
     */
    public function search(array $query, $from = 0, $size = 20) : array {

        $result = $this->client->search([
            'size'  => $size,
            'from'  => $from,
            'index' => $this->index,
            'body' => [
                'query' => $query
            ]
        ]);

        return self::format($result);
    }

    private static function format($res) : array{
        $docs =  $res['hits']['hits'];
        $arr = [];
        foreach ($docs as $key => $doc) {
            $arr[$key] = $doc['_source'];
            $arr[$key]['_id'] = $doc['_id'];
        }
        return $arr;
    }
}
